package com.tengju.settlement.infrastructure.repository;

import com.tengju.data.domain.shared.CastUtil;
import com.tengju.settlement.domain.model.account.*;
import com.tengju.settlement.infrastructure.persistence.mybatis.dataobject.AccountDO;
import com.tengju.settlement.infrastructure.persistence.mybatis.mapper.tengju.custom.AccountDOMapper;
import com.tengju.settlement.infrastructure.repository.convert.AccountConvert;
import com.tengju.settlement.infrastructure.shared.InfraException;
import org.springframework.stereotype.Repository;

@Repository
public class AccountRepositoryImpl implements AccountRepository {

    private final AccountDOMapper accountDOMapper;

    public AccountRepositoryImpl(AccountDOMapper accountDOMapper) {
        this.accountDOMapper = accountDOMapper;
    }

    @Override
    public Account find(UserIdCode userIdCode, AccountType accountType) {
        AccountDO accountDO = accountDOMapper.selectByIdCode(userIdCode.getValue());
        return AccountConvert.convert(accountDO);
    }

    @Override
    public Account findByAccountId(AccountId accountId) {
        AccountDO accountDO = accountDOMapper
                .selectByPrimaryKey(CastUtil.castInt(accountId.getValue()));
        return AccountConvert.convert(accountDO);
    }

    @Override
    public void save(Account account) {
        AccountDO accountDO = AccountConvert.convert(account);
        accountDOMapper.insertSelective(accountDO);
    }

    @Override
    public Account findOrSave(UserIdCode idCode, AccountType accountType) {
        Account account = find(idCode, accountType);
        if (account == null) {
            account = Account.newAccount(idCode);
            save(account);
        }
        return account;
    }

    @Override
    public void updateBalance(Account account, Integer oldVersion) {
        AccountDO accountDO = AccountConvert.convert(account);
        int count = accountDOMapper.updateBalanceById(accountDO, oldVersion);
        if (count != 1) {
            throw new InfraException("余额变更失败，accountId:" + accountDO.getId());
        }

    }

}
